package com.example.maybeaccount.Entry;

import androidx.appcompat.app.AppCompatActivity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.example.maybeaccount.AddItem;
import com.example.maybeaccount.Mode.ActivityController;
import com.example.maybeaccount.Mode.SqliteDB;
import com.example.maybeaccount.R;

import java.util.ArrayList;
import java.util.List;

/**
 * 图形密码解锁
 */
public class NineGridUnlock extends AppCompatActivity implements LockPatternView.OnPatternChangeListener {

    private LockPatternView lpv;
    private TextView tv;
    private int firstFlag = 0;
    private boolean isTop;
    private TextView textOthers;
    private List<User> userList = new ArrayList<>();
    private User user;
    private boolean isSetting = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initBroadcast();
        setContentView(R.layout.ninegridunlock);

        lpv = (LockPatternView) findViewById(R.id.lock_pattern_view);
        tv = (TextView) findViewById(R.id.text);
        lpv.setOnPatternChangeListener(this);
        textOthers = findViewById(R.id.others);

        userList = SqliteDB.getInstance(getApplicationContext()).loadUser();
        user = userList.get(0);
        if(getIntent().getIntExtra("setting",0)==1){
            if(user.getGridPwd().equals("00000")){
                //暂未设置图形密码
                Intent intent= new Intent(NineGridUnlock.this, NineGridSetting.class);
                startActivity(intent);
                finish();
            }else {
                isSetting = true;
                tv.setText("请绘制旧密码");
                textOthers.setVisibility(View.GONE);
            }

        }



        textOthers.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(NineGridUnlock.this,Entrance.class);
                startActivity(intent);
            }
        });
    }


    @Override
    public void onPatternChange(String patternPassword) {
        if (patternPassword == null) {
            tv.setTextColor(Color.parseColor("#18b968"));
            lpv.clearDraw();
            tv.setTextColor(Color.RED);
            tv.setText("请至少5个点");
        } else {

            if(user.getGridPwd().equals(patternPassword)){
                tv.setTextColor(Color.parseColor("#18b968"));
                tv.setText("密码正确");
                if(isSetting){
                    Intent intent= new Intent(NineGridUnlock.this, NineGridSetting.class);
                    startActivity(intent);
                    finish();
                }else{
                    Toast.makeText(getApplicationContext(),"登录成功",Toast.LENGTH_LONG).show();
                    //获取Intent，判断是否来自shortcut
                    Intent intent1 = getIntent();
                    String flag = intent1.getStringExtra("shortflag");
                    if(flag != null && flag.equals("short")){
                        Intent intent= new Intent(NineGridUnlock.this, AddItem.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(intent);
                    } else {
                        ActivityController.resumeActivity(this,this);
                    }
                }
            }else{
                tv.setTextColor(Color.RED);
                tv.setText("密码错误");
            }
        }
    }

    @Override
    public void onPatternStarted(boolean isStarted) {
        if (isStarted) {
            tv.setTextColor(Color.parseColor("#18b968"));
            tv.setText("请绘制图案");
        }
    }

    /**
     * 后台唤醒后进入密码界面
     */
    @Override
    protected void onResume(){
        super.onResume();
        isTop = true;
        if(firstFlag == 1 && isSetting){
            firstFlag = 0;
            Intent intent = new Intent(NineGridUnlock.this, Entrance.class);
            intent.putExtra("resume","Member");
            startActivity(intent);
        }else{
            firstFlag = 0;
        }
    }


    /** 广播监听home和menu */
    class InnerRecevier extends BroadcastReceiver {
        final String SYSTEM_DIALOG_REASON_KEY = "reason";
        final String SYSTEM_DIALOG_REASON_RECENT_APPS = "recentapps";
        final String SYSTEM_DIALOG_REASON_HOME_KEY = "homekey";

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (Intent.ACTION_CLOSE_SYSTEM_DIALOGS.equals(action)) {

                String reason = intent.getStringExtra(SYSTEM_DIALOG_REASON_KEY);

                if (reason != null) {

                    if (reason.equals(SYSTEM_DIALOG_REASON_HOME_KEY) && isTop) {
                        // "Home键被监听"
                        firstFlag = 1;

                    } else if (reason.equals(SYSTEM_DIALOG_REASON_RECENT_APPS) && isTop) {
                        //"多任务键被监听"
                        firstFlag = 1;

                    }
                }
            }
        }
    }

    private void initBroadcast(){
        /** 广播 */
        this.getWindow().setFlags(0x80000000,0x80000000);
        //创建广播
        InnerRecevier innerReceiver = new InnerRecevier();
        //动态注册广播
        IntentFilter intentFilter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
        //启动广播
        registerReceiver(innerReceiver, intentFilter);
    }

    /**
     * 重写返回键 直接退出程序
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode== android.view.KeyEvent.KEYCODE_BACK && !isSetting){
            Intent home = new Intent(Intent.ACTION_MAIN);
            home.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            home.addCategory(Intent.CATEGORY_HOME);
            startActivity(home);
        }else if(keyCode== android.view.KeyEvent.KEYCODE_BACK && isSetting){
            finish();
        }
        return true;
    }
}
